/**
 * User: alesj
 * Date: 2004.8.25
 * Time: 12:44:03
 */

package com.generalynx.common.web.tags;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import java.lang.reflect.Method;
import java.util.Collection;

public class VoidCollectionHandlerTag extends TagSupport {

    protected static final Log logger = LogFactory.getLog(VoidCollectionHandlerTag.class);

    public int doStartTag() throws JspException {
        try {
            logger.debug(handleCollection());
            return super.doStartTag();
        } catch (Exception e) {
            throw new JspException(e);
        }
    }

    protected Object handleCollection() throws Exception {
        Collection collection = (Collection)pageContext.getAttribute(getCol(), TagUtils.getScope(getColscope()));
        Class[] parameterTypes = new Class[]{};
        Object[] args = new Object[]{};
        if (getVar() != null) {
            Object var = getBean(getVar());
            Class clazz = (getMethod().endsWith("All") ? Collection.class : Object.class);
            parameterTypes = new Class[]{clazz};
            args = new Object[]{var};
        }
        Method m = collection.getClass().getMethod(getMethod(), parameterTypes);
        return m.invoke(collection, args);
    }

    private Object getBean(String var) {
        int p = var.indexOf('.');
        String beanName = var;
        if (p > 0) {
            beanName = var.substring(0, p);
        }
        Object beanObject = pageContext.getAttribute(beanName, TagUtils.getScope(getVarscope()));
        if (p > 0) {
            BeanWrapper bw = new BeanWrapperImpl(beanObject);
            return bw.getPropertyValue(var.substring(p + 1));
        } else {
            return beanObject;
        }
    }

    public String getCol() {
        return m_col;
    }

    public void setCol(String col) {
        m_col = col;
    }

    public String getMethod() {
        return m_method;
    }

    public void setMethod(String method) {
        m_method = method;
    }

    public String getVar() {
        return m_var;
    }

    public void setVar(String var) {
        m_var = var;
    }

    public String getColscope() {
        return m_colscope;
    }

    public void setColscope(String colscope) {
        m_colscope = colscope;
    }

    public String getVarscope() {
        return m_varscope;
    }

    public void setVarscope(String varscope) {
        m_varscope = varscope;
    }

    private String m_col;
    private String m_method;
    private String m_var;
    private String m_colscope = TagUtils.SCOPE_REQUEST;
    private String m_varscope = TagUtils.SCOPE_REQUEST;

}
